﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

internal class Program
{
    private static async Task Main(string agg)
    {
        const string serverIp = "127.0.0.1";
        const int serverPort = 13000;

        try
        {
            using (var client = new TcpClient())
            {
                // 连接服务器，设置超时时间
                var ar = client.BeginConnect(serverIp, serverPort, null, null);
                var wh = ar.AsyncWaitHandle;

                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                    {
                        client.Dispose();
                        throw new TimeoutException();
                    }

                    client.EndConnect(ar);
                }
                finally
                {
                    wh.Dispose();
                }

                var stream = client.GetStream();

                // 发送数据
                var dataToSend = Encoding.UTF8.GetBytes("Hello, Server!\n");
                await stream.WriteAsync(dataToSend, 0, dataToSend.Length);

                // 接收数据
                var receivedData = new byte[256];
                var completeMessage = new StringBuilder();
                var bytesReceived = 0;

                do
                {
                    bytesReceived = await stream.ReadAsync(receivedData, 0, receivedData.Length);
                    completeMessage.AppendFormat("{0}", Encoding.UTF8.GetString(receivedData, 0, bytesReceived));
                } while (stream.DataAvailable);

                Console.WriteLine("Received from server: " + completeMessage);
            }
        }
        catch (SocketException se)
        {
            Console.WriteLine("SocketException: " + se);
        }
        catch (TimeoutException te)
        {
            Console.WriteLine("TimeoutException: " + te);
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e);
        }
    }


    private static async Task Main()
    {
        const string serverIp = "127.0.0.1";
        const int serverPort = 13000;

        try
        {
            using (var client = new TcpClient())
            {
                var args = new SocketAsyncEventArgs();
                args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
                args.Completed += (sender, eventArgs) =>
                {
                    if (eventArgs.SocketError != SocketError.Success)
                    {
                        Console.WriteLine("Failed to connect: " + eventArgs.SocketError);
                        return;
                    }

                    var stream = client.GetStream();

                    // 发送数据
                    var dataToSend = Encoding.UTF8.GetBytes("Hello, Server!\n");
                    stream.Write(dataToSend, 0, dataToSend.Length);

                    // 接收数据
                    var receivedData = new byte[256];
                    var completeMessage = new StringBuilder();
                    var bytesReceived = 0;

                    do
                    {
                        bytesReceived = stream.Read(receivedData, 0, receivedData.Length);
                        completeMessage.AppendFormat("{0}", Encoding.UTF8.GetString(receivedData, 0, bytesReceived));
                    } while (stream.DataAvailable);

                    Console.WriteLine("Received from server: " + completeMessage);
                };

                client.Client.ConnectAsync(args);
                await Task.Delay(-1); // Keep the application running
            }
        }
        catch (SocketException se)
        {
            Console.WriteLine("SocketException: " + se);
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e);
        }
    }
}